#!/bin/bash

# 添加www子域名到SSL证书
# 扩展现有证书以支持www.pecco.pet

set -e

# 颜色输出
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

log_info() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

log_warn() {
    echo -e "${YELLOW}[WARN]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

print_title() {
    echo -e "${BLUE}"
    echo "=================================================="
    echo "    添加 www.pecco.pet 到SSL证书"
    echo "=================================================="
    echo -e "${NC}"
}

# 检查当前证书
check_current_cert() {
    log_info "检查当前证书状态..."
    
    if [ -f "/etc/letsencrypt/live/pecco.pet/fullchain.pem" ]; then
        log_info "当前证书信息:"
        openssl x509 -in /etc/letsencrypt/live/pecco.pet/fullchain.pem -text -noout | grep -A 1 "Subject Alternative Name" || echo "未找到SAN信息"
        
        log_info "证书过期时间:"
        openssl x509 -in /etc/letsencrypt/live/pecco.pet/fullchain.pem -enddate -noout
    else
        log_error "未找到现有证书"
        exit 1
    fi
}

# 方案1：扩展现有证书（推荐）
expand_existing_cert() {
    log_info "方案1: 扩展现有证书以包含www子域名"
    
    # 停止nginx
    log_info "临时停止nginx容器..."
    docker-compose -f docker-compose.prod.yml stop nginx
    
    # 扩展证书
    log_info "扩展证书以包含www.pecco.pet..."
    certbot certonly \
        --standalone \
        --non-interactive \
        --agree-tos \
        --expand \
        --cert-name pecco.pet \
        -d pecco.pet \
        -d www.pecco.pet
    
    if [ $? -eq 0 ]; then
        log_info "证书扩展成功"
        return 0
    else
        log_error "证书扩展失败"
        return 1
    fi
}

# 方案2：使用webroot模式扩展证书
expand_cert_webroot() {
    log_info "方案2: 使用webroot模式扩展证书"
    
    # 创建临时nginx配置支持验证
    cat > /tmp/nginx-verify.conf << 'EOF'
# HTTP服务器 - 支持Let's Encrypt验证
server {
    listen 80;
    server_name pecco.pet www.pecco.pet 124.220.186.165;
    
    # Let's Encrypt验证路径
    location /.well-known/acme-challenge/ {
        root /var/www/certbot;
    }
    
    # 其他请求重定向到HTTPS
    location / {
        return 301 https://pecco.pet$request_uri;
    }
}

# HTTPS服务器
server {
    listen 443 ssl http2;
    server_name pecco.pet www.pecco.pet 124.220.186.165;

    # SSL证书配置
    ssl_certificate /etc/nginx/ssl/fullchain.pem;
    ssl_certificate_key /etc/nginx/ssl/privkey.pem;
    
    # SSL安全配置
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES128-SHA256:ECDHE-RSA-AES256-SHA384:ECDHE-RSA-AES128-SHA:ECDHE-RSA-AES256-SHA:DHE-RSA-AES128-SHA256:DHE-RSA-AES256-SHA256:DHE-RSA-AES128-SHA:DHE-RSA-AES256-SHA:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!MD5:!PSK:!SRP:!CAMELLIA;
    ssl_prefer_server_ciphers on;
    ssl_session_cache shared:SSL:10m;
    ssl_session_timeout 10m;
    
    # 安全头
    add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
    add_header X-Frame-Options DENY always;
    add_header X-Content-Type-Options nosniff always;
    add_header X-XSS-Protection "1; mode=block" always;
    add_header Referrer-Policy "strict-origin-when-cross-origin" always;

    # 设置客户端最大请求体大小
    client_max_body_size 100M;

    # 静态文件服务
    location /static/ {
        alias /app/pecco_backend/staticfiles/;
        expires 30d;
        add_header Cache-Control "public, immutable";
    }

    # 媒体文件服务
    location /media/ {
        alias /app/pecco_backend/media/;
        expires 30d;
        add_header Cache-Control "public, immutable";
    }

    # Django应用反向代理
    location / {
        proxy_pass http://web:8000;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto https;
        proxy_set_header X-Forwarded-Port 443;
        
        # 超时设置
        proxy_connect_timeout 60s;
        proxy_send_timeout 60s;
        proxy_read_timeout 60s;
    }
}
EOF
    
    # 更新nginx配置
    cp /tmp/nginx-verify.conf nginx.conf
    
    # 确保webroot目录存在
    mkdir -p ./certbot-webroot
    
    # 重启nginx以支持验证
    log_info "重启nginx以支持Let's Encrypt验证..."
    docker-compose -f docker-compose.prod.yml up -d nginx
    
    # 等待nginx启动
    sleep 10
    
    # 使用webroot模式扩展证书
    log_info "使用webroot模式扩展证书..."
    certbot certonly \
        --webroot \
        --webroot-path=./certbot-webroot \
        --non-interactive \
        --agree-tos \
        --expand \
        --cert-name pecco.pet \
        -d pecco.pet \
        -d www.pecco.pet
    
    local result=$?
    
    if [ $result -eq 0 ]; then
        log_info "webroot模式证书扩展成功"
        return 0
    else
        log_error "webroot模式证书扩展失败"
        return 1
    fi
}

# 复制新证书
copy_new_certificates() {
    log_info "复制新证书文件..."
    
    if [ -f "/etc/letsencrypt/live/pecco.pet/fullchain.pem" ]; then
        cp /etc/letsencrypt/live/pecco.pet/fullchain.pem ./ssl-certs/
        cp /etc/letsencrypt/live/pecco.pet/privkey.pem ./ssl-certs/
        chmod 644 ./ssl-certs/fullchain.pem
        chmod 600 ./ssl-certs/privkey.pem
        log_info "新证书复制完成"
        return 0
    else
        log_error "新证书文件不存在"
        return 1
    fi
}

# 验证新证书
verify_new_cert() {
    log_info "验证新证书..."
    
    # 重启nginx
    log_info "重启nginx..."
    docker-compose -f docker-compose.prod.yml restart nginx
    
    # 等待nginx启动
    sleep 15
    
    # 检查证书中的域名
    log_info "检查新证书包含的域名:"
    openssl x509 -in ./ssl-certs/fullchain.pem -text -noout | grep -A 1 "Subject Alternative Name"
    
    # 测试两个域名的HTTPS连接
    log_info "测试 pecco.pet HTTPS连接:"
    if curl -s -I "https://pecco.pet" | grep -q "200"; then
        log_info "✓ pecco.pet HTTPS正常"
    else
        log_warn "✗ pecco.pet HTTPS可能有问题"
    fi
    
    log_info "测试 www.pecco.pet HTTPS连接:"
    if curl -s -I "https://www.pecco.pet" | grep -q "200"; then
        log_info "✓ www.pecco.pet HTTPS正常"
    else
        log_warn "✗ www.pecco.pet HTTPS可能有问题"
    fi
}

# 主函数
main() {
    print_title
    
    # 检查权限
    if [ "$EUID" -ne 0 ]; then
        log_error "请使用root权限运行此脚本: sudo $0"
        exit 1
    fi
    
    check_current_cert
    
    echo
    log_info "选择扩展证书的方法:"
    echo "1. 使用standalone模式扩展证书 (需要临时停止nginx)"
    echo "2. 使用webroot模式扩展证书 (不停止服务)"
    echo "3. 取消操作"
    echo -n "请选择 (1-3): "
    read choice
    
    case $choice in
        1)
            if expand_existing_cert; then
                copy_new_certificates
                verify_new_cert
                log_info "✅ www.pecco.pet 已成功添加到SSL证书！"
                echo
                echo "现在您可以通过以下地址访问网站:"
                echo "• https://pecco.pet"
                echo "• https://www.pecco.pet"
            else
                log_error "证书扩展失败"
                # 确保nginx重新启动
                docker-compose -f docker-compose.prod.yml start nginx
            fi
            ;;
        2)
            if expand_cert_webroot; then
                copy_new_certificates
                verify_new_cert
                log_info "✅ www.pecco.pet 已成功添加到SSL证书！"
                echo
                echo "现在您可以通过以下地址访问网站:"
                echo "• https://pecco.pet"
                echo "• https://www.pecco.pet"
            else
                log_error "证书扩展失败"
            fi
            ;;
        3)
            log_info "操作已取消"
            ;;
        *)
            log_error "无效选择"
            ;;
    esac
}

# 运行主函数
main "$@"
